package cn.itcast.bos.service.base.impl;

import java.util.List;
import java.util.Set;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.dao.base.CourierRepository;
import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.service.CourierService;

@Service
@Transactional
public class CourierServiceImpl implements CourierService {

	//注入DAO
	@Autowired
	private CourierRepository courierRepository;
	
	//添加快递员
	@Override
	public void save(Courier courier) {
		courierRepository.save(courier);
	}

	//条件分页查询快递员
	@Override
	public Page<Courier> pageQuery(Specification<Courier> specification,Pageable pageable) {
		return courierRepository.findAll(specification,pageable);
	}

	//批量作废快递员
	@Override
	public void delBatch(String[] idArray) {		
		
		//循环遍历获取数组中的每个Id,并转换为Integer类型
		for (String idStr : idArray) {
			Integer id = Integer.parseInt(idStr);
			
			//调用DAO实现update修改操作，将deltag修改为1
			courierRepository.update(id);
		}
	}

	//查询未关联定区快递员(条件查询，无分页)
	@Override
	public List<Courier> findNoAssociationCourier() {
		
		//构造条件查询对象
		Specification<Courier> specification = new Specification<Courier>() {

			@Override
			public Predicate toPredicate(Root<Courier> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				
				//查询条件：判断siez是否为空
				Predicate p1 = cb.isEmpty(root.get("fixedAreas").as(Set.class));
				return p1;
			}
		};
		return courierRepository.findAll(specification);
	}

}
